package com.asset.service.impl;

import com.asset.mapper.RoleMapper;
import com.asset.pojo.Role;
import com.asset.service.RoleService;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author 11725
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public PageResult<Role> selectByPage(Integer page, Integer rows, String keyWord, Boolean selectAll) {
        // 是否可进行分页
        if (selectAll == null) {
            PageHelper.startPage(page, rows);
        }
        Example example = new Example(Role.class);

        // 是否存在详情关键字
        if (keyWord != null && keyWord.trim().length() != 0) {
            example.createCriteria().andLike("detail", "%" + keyWord + "%");
        }

        // 查询
        List<Role> roles = roleMapper.selectByExample(example);

        PageInfo<Role> info = new PageInfo<>(roles);
        return new PageResult<>(info.getTotal(), roles);
    }

    @Override
    public List<Role> selectByUserId(Long userId) {
        return roleMapper.selectByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserRoles(Long userId, List<Long> roleList) {
        // 1. 删除用户所有角色
        roleMapper.deleteByUid(userId);
        // 2. 逐条新增
        Set<Long> roleSet = new HashSet<>(roleList);
        for (Long roleId : roleSet) {
            roleMapper.insertForUser(userId, roleId);
        }
    }
}
